//自调用函数封闭作用域
(function(){
    var that = this;


    function Game(map){
        // 设置三个属性存储食物、蛇和地图；
        this.food = new Food;
        this.snake = new Snake;
        this.map = map;
        that = this;
    }
    //添加一个游戏开始的方法，方法内初始化蛇和食物
    Game.prototype.start = function(){
        //1.添加蛇和食物到地图上
        this.food.render(this.map);
        this.food.render(this.map);
        this.food.render(this.map);
        this.snake.render(this.map);
        runSnake();
        
        bingKey();
    };

    //添加一个私有函数控制上下左右按键更改的方向
    function bingKey(){
        //给文档绑定键盘按下按键
        document.onkeydown = function(e){
            // console.log(e.keyCode);
            //键盘的编码
            // 38 -- bottom 
            // 40 -- top
            // 37 -- left
            // 39 -- right
            switch(e.keyCode){
                case 38 : 
                    that.snake.direction = "bottom";
                    break;
                case 40 : 
                    that.snake.direction = "top";
                    break;
                case 37 : 
                    that.snake.direction = "left";
                    break;
                case 39 : 
                    that.snake.direction = "right";
                    break;
            }
        };
    }

    //添加一个蛇运动的方法
    function runSnake(){
        var timer = setInterval(function(){
            //2.让游戏逻辑开始
            that.snake.move();
            that.snake.remove(this.map);
            that.snake.render(this.map);

            maxX = that.map.offsetWidth / that.snake.width;
            maxY = that.map.offsetHeight / that.snake.height;

            headX = that.snake.body[0].x;
            headY = that.snake.body[0].y;

            foodX = that.food.x;
            foodY = that.food.y;

            hX = that.snake.body[0].x * that.snake.width;
            hY = that.snake.body[0].y * that.snake.height;
                
            for(var i = 0; i<that.food.elements.length; i++){
                if(hX === that.food.elements[i].offsetLeft && hY === that.food.elements[i].offsetTop){
                that.food.remove(that.map,i);
                that.food.render(that.map);

                var last = that.snake.body[that.snake.body.length - 1];
                that.snake.body.push({
                    x : last.x,
                    y : last.y,
                    color : last.color
                })
                }
            }
            

            if(headX <0 || headX >= maxX || headY<0 || headY >= maxY){
                //停止定时器
                clearInterval(timer);
                //弹出提示
                alert("Game Over");
            }
        },150);

        
    }
    //将构造函数通过window暴露
    window.Game = Game;
})();


